<?php

namespace App\Http\Controllers\Admin;

use App\Helpers\ExcelExportTrait;
use App\Model\OrderChart;
use App\Model\UserChart;
use App\Model\VisitByDate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ChartController extends BaseController
{
    use ExcelExportTrait;

    private $start_datetime;
    private $start_date;
    private $end_datetime;
    private $end_date;
    private $today_date;
    private $request;
    private $export=false;

    public function __construct(Request $request)
    {
        //今日日期
        $this->today_date = date('Y-m-d');

        //开始时间，默认七天前
        if ($start = $request->input('start')) {
            $this->start_date = date('Y-m-d',strtotime($start));
        }else{
            $this->start_date = date('Y-m-d',strtotime('-7 day'));
        }

        //结束时间，不能大于今天，默认一天前
        if ($end = $request->input('end')) {
            $date = date('Y-m-d',strtotime($end));
            $this->end_date = $date < $this->today_date?$date:$this->today_date;
        }else{
            $this->end_date = date('Y-m-d',strtotime('-1 day'));
        }

        //是否导出
        if ($request->input('export') == "true"){
            $this->export = true;
        }

        //开始日期不能大于结束日期
        if ($this->start_date > $this->end_date) {
            $this->start_date = $this->end_date;
        }

        $this->start_datetime = $this->start_date.' 00:00:00';
        $this->end_datetime = $this->end_date.' 23:59:59';
        $this->request = $request;
    }

    //浏览数据
    public function visitChart()
    {
        $reqDates = $this->getDateBetweenStartAndEnd($this->start_date,$this->end_date);

        $orgDates = DB::table('sys_visit_by_date')->where('date','>=',$this->start_date)
            ->where('date','<=',$this->end_date)
            ->whereNull('deleted_at')
            ->where('obj_type','=',2)
            ->pluck('date')->toArray();

        $dates = array_diff($reqDates,$orgDates);

        foreach ($dates as $date) {
            VisitByDate::updateByDate($date,2);
        }

        if (in_array($this->today_date,$reqDates)) {
            VisitByDate::updateByDate($this->today_date,2);
        }

        $query = VisitByDate::where('date','>=',$this->start_date)
            ->where('date','<=',$this->end_date)
            ->where('obj_type','=',2)
            ->orderBy('date','desc');


        if ($this->export) {

            $items = $query->select('date as 日期','total as 葡萄酒详情页总浏览量','qr_pv as 二维码来源浏览量',
                'qr_uv as 二维码来源浏览人数','pv as 普通来源浏览量','uv as 普通来源浏览人数')
                ->get()->toArray();

            $style = [];
            $style['width'] = array('A' => 20,'B' => 20,'C' => 20,'D' => 20,'E' => 20,'F' => 20);

            return $this->exportFile('浏览数据 - '.date('Ymd'),$items,"xlsx",$style);
        }

        $items = $query->get();

        return $this->success($items);

    }

    //订单数据
    public function orderChart()
    {
        $reqDates = $this->getDateBetweenStartAndEnd($this->start_date,$this->end_date);

        $orgDates = DB::table('order_charts')->where('date','>=',$this->start_date)
            ->where('date','<=',$this->end_date)
            ->whereNull('deleted_at')
            ->pluck('date')->toArray();

        $dates = array_diff($reqDates,$orgDates);

        foreach ($dates as $date) {
            OrderChart::updateByDate($date);
        }

        if (in_array($this->today_date,$reqDates)) {
            OrderChart::updateByDate($this->today_date);
        }

        $query = OrderChart::where('date','>=',$this->start_date)
            ->where('date','<=',$this->end_date)
            ->orderBy('date','desc');


        if ($this->export) {

            $items = $query->select('date as 日期','total as 全部订单量','total_fee as 订单总金额',
                'general_quantity as 普通订单成交量','gift_quantity as 赠礼订单成交量','qr_general_quantity as 二维码来源普通订单',
                'qr_gift_quantity as 二维码来源赠礼订单')
                ->get()->toArray();

            $style = [];
            $style['width'] = array('A' => 20,'B' => 20,'C' => 20,'D' => 20,'E' => 20,'F' => 20,'G' => 20);

            return $this->exportFile('订单数据 - '.date('Ymd'),$items,"xlsx",$style);
        }

        $items = $query->get();

        return $this->success($items);
    }

    //新增数据
    public function newChart()
    {
        //type : view浏览|order订单
        $type = $this->request->input('type','view');

        if (!in_array($type,['view','order'])){
            return $this->failed('type '.$type.' not allowed');
        }

        $fields = [
            'export' => [
                'view' => ['date as 日期','view_total as 新增用户','view_qr_total as 二维码来源新增','view_other_total as 其他来源新增'],
                'order' => ['date as 日期','order_total as 新增用户','order_qr_total as 二维码来源新增','order_other_total as 其他来源新增']
            ],
            'show' => [
                'view' => ['date','view_total as count','view_qr_total as qrcode','view_other_total as other'],
                'order' => ['date','order_total as count','order_qr_total as qrcode','order_other_total as other'],
            ]

        ];

        $reqDates = $this->getDateBetweenStartAndEnd($this->start_date,$this->end_date);

        $orgDates = DB::table('sys_user_charts')->where('date','>=',$this->start_date)
            ->where('date','<=',$this->end_date)
            ->whereNull('deleted_at')
            ->pluck('date')->toArray();

        $dates = array_diff($reqDates,$orgDates);

        foreach ($dates as $date) {
            UserChart::updateByDate($date);
        }

        if (in_array($this->today_date,$reqDates)) {
            UserChart::updateByDate($this->today_date);
        }

        $query = UserChart::where('date','>=',$this->start_date)
            ->where('date','<=',$this->end_date)
            ->orderBy('date','desc');

        if ($this->export) {

            $items = $query->select($fields['export'][$type])
                ->get()->toArray();

            $style = [];
            $style['width'] = array('A' => 20,'B' => 20,'C' => 20,'D' => 20);

            return $this->exportFile(($type=="view"?"浏览":"订单").'新增用户 - '.date('Ymd'),$items,"xlsx",$style);
        }

        $items = $query->select($fields['show'][$type])->get();

        return $this->success($items);
    }

    public function getDateBetweenStartAndEnd($start,$end)
    {
        $date = [];
        while ($end >= $start ){
            $date[] = $end;
            $end = date('Y-m-d',strtotime($end) - 24*3600);
        }
        return $date;
    }

    public function updateByDate($start,$end,$cb)
    {
        $date = $end;
        while ($date >= $start ){
            $bool = $cb($date);
            if (!$bool) break;
            $date = date('Y-m-d',strtotime($date) - 24*3600);
        }
    }
}
